package com.ktg.mes.unit.sql.domain;

import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import lombok.Data;
import lombok.experimental.Accessors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;


/**
 * 收录生产警告警告对象 pro_waring
 *
 * @author byteco
 * @date 2022-11-28
 */


@Data
@Accessors(chain = true)
public class SQLToolModel implements Serializable
{

    private static final Logger log = LoggerFactory.getLogger(SQLToolModel.class);
    private String sqlType = null;
    private String dbName = null;
    private SQLDBConfig sqldbConfig;


    private String tableName;

    private List<String> colums = new ArrayList<>();
    private List<Object> values = new ArrayList<>();

    private Map updateMap = new HashMap<>();

    private List<Map> columnAsMap = new ArrayList<>();

    private Map whereMap = new HashMap<>();

    private List<String> whereStrList = new ArrayList<>();
    private Integer size = null;

    private String orderByColumn;

    private boolean isInsertCanBlack = false; //false 代表不能为 '' true 代表为""

    private boolean isMapNULL = false;

    private Map<String, MTableColumn> columnType = null;


    public SQLToolModel(SQLDBConfig sqldbConfig, String tableName, Map<String, MTableColumn> map){
        setTable(sqldbConfig,tableName,map);
    }

    public SQLToolModel(SQLDBConfig sqldbConfig, String tableName){
        setTable(sqldbConfig,tableName,null);
    }
    public void setTable(SQLDBConfig sqldbConfig,String tableName,Map<String, MTableColumn> map){
        sqlType = sqldbConfig.getSqlType();
        this.sqldbConfig = sqldbConfig;
        this.dbName = sqldbConfig.getDbName();
        this.tableName = tableName;
        this.columnType = map;
    }
    public void insertColumAndValue(String colum,Object value){
        Object obj = value;
        if (obj == null){
            return;
        }
        try{
            obj = valueObject(colum,value);
            if (obj != null && obj instanceof String){
                if (!isInsertCanBlack){
                    if (!StringUtils.isEmpty(((String) obj))){
                        colums.add(colum);
                        values.add(obj);
                    }
                }else {
                    colums.add(colum);
                    values.add(obj);
                }
            }else if (obj != null){
                colums.add(colum);
                values.add(obj);
            }
        }catch (Exception e){
            log.error("SQLTool",e);
        }
    }

    public Object valueObject(String colum,Object value){
        Object obj = value;
        if (obj == null){
            return null;
        }
        if (columnType != null){
            String type = columnType.get(colum).getType();
            if (sqldbConfig.getType() == SQLCType.PGSQL){
                if ("timestamp".equals(type) || type.equals("time")){
                    obj = DateUtils.parseDate(obj);
                }else if(type.startsWith("int")){
                    obj = Long.valueOf(obj.toString());
                }else if (type.startsWith("float") || type.startsWith("float")){
                    obj = Double.valueOf(obj.toString());
                }else if (type.equals("numeric")){
                    obj = BigDecimal.valueOf(Double.valueOf(obj.toString()));
                }else{
                    obj = String.valueOf(obj.toString());
                }
            }else {
                if ("datetime".equals(type)){
                    obj = DateUtils.parseDate(obj);
                }else if("bigint".equals(type) || "int".equals(type)){
                    obj = Long.valueOf(obj.toString());
                }else if ("double".equals(type)){
                    obj = Double.valueOf(obj.toString());
                }else if ("decimal".equals(type)){
                    obj = BigDecimal.valueOf(Double.valueOf(obj.toString()));
                }
            }
        }
        return obj;
    }
    public void updateColumAndValue(String colum,Object value){
        value = valueObject(colum,value);
        updateMap.put(colum,value);

    }

    public void addWhere(String colum,Object value){
        String key = colum.replace(" ","");
        whereMap.put(key+" = ",valueObject(key,value));
    }

    public void addWhere(String colum,String than,Object value){
        String key = colum.replace(" ","");
        than = than.replace(" ","");
        whereMap.put(key+" "+than+" ",valueObject(key,value));
    }


    public void addWhere(String whereStr){
        this.whereStrList.add(whereStr);
    }

    public void  addColumns(String column){
        for (int i = 0; i < colums.size(); i++) {
            if (colums.get(i).equals(column)){
                return;
            }
        }
        colums.add(column);
    }

    public void addColumnAs(String colum,String toColumn){
        if (colum.equals(toColumn)){
            addColumns(colum);
        }else {
            Map map = new HashMap<>();
            map.put(colum,toColumn);
            this.columnAsMap.add(map);
        }

    }

    /**
     * 将驼峰命名转化成下划线
     * @param para
     * @return
     */
    public String camelToUnderline(String para){
        if(para.length()<3){
            return para.toLowerCase();
        }
        StringBuilder sb=new StringBuilder(para);
        int temp=0;//定位
        //从第三个字符开始 避免命名不规范
        for(int i=2;i<para.length();i++){
            if(Character.isUpperCase(para.charAt(i))){
                sb.insert(i+temp, "_");
                temp+=1;
            }
        }
        String str = sb.toString().toLowerCase();
        if (str.endsWith("[0]")){
            str.substring(0,str.length()-3);
        }
        return str;
    }






}
